import 'dart:convert';

import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/common_search/bean/bean_common_search.dart';
import 'package:dk_flutter_module_sale/common/common_search/bean/event_bus_search_result.dart';
import 'package:dk_flutter_module_sale/r.dart';
import 'package:dk_flutter_module_sale/sale/sale_out/watch_plan/bean/bean_data_commonlist_config.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter_device_info/flutter_device_info.dart';
import 'package:dk_flutter_module_sale/config/cache_info_key.dart';

class SearchContentBloc extends EventBloc<String> {
  final String placeholder;

  SearchContentBloc(this.placeholder);

  @override
  String get initialState => placeholder;
}

class CommonSearchContent extends StatefulWidget {
  final SearchData searchData;
  final EventBus eventBus;

  CommonSearchContent(this.searchData, this.eventBus);

  @override
  State<CommonSearchContent> createState() {
    return CommonSearchContentState();
  }
}

class CommonSearchContentState extends State<CommonSearchContent> {
  SearchContentBloc bloc;
  bool isDimSearch;

  CommonSearchContentState();

  @override
  void initState() {
    super.initState();
    isDimSearch = checkBool(objEmpty(widget.searchData) ||
        stringEmpty(widget.searchData.type) ||
        widget.searchData.type == "dim");
    bloc = SearchContentBloc("");
    widget.eventBus?.on<SearchResultEvent>()?.listen((SearchResultEvent event) {
      bloc?.dispatch(event?.content);
    });
    // 处理空搜索
    widget.eventBus?.on<SubmitEvent>()?.listen((SubmitEvent event){
      if(stringBlank(event.content)){
        RouteUtil.pop(context, result: {
          "searchKey": widget.searchData?.dimKey,
          "searchValue": event.content,
          "displayName": event.content,
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder(
      bloc: bloc,
      builder: (BuildContext context, String outSetContent) {
        //模糊搜索
        if (isDimSearch) {
          return CommonSearchHistory(
              isDimSearch, widget.searchData, widget.eventBus, outSetContent);
        }
        //精确搜索
        return stringBlank(outSetContent)
            ? CommonSearchHistory(
                isDimSearch, widget.searchData, widget.eventBus, outSetContent)
            : CommonSearchSelect(widget.searchData, outSetContent);
      },
    );
  }
}

class CommonSearchHistory extends StatefulWidget {
  final bool isDimSearch;
  final SearchData searchData;
  final EventBus eventBus;
  final String outSetContent;

  CommonSearchHistory(
      this.isDimSearch, this.searchData, this.eventBus, this.outSetContent);

  @override
  State<CommonSearchHistory> createState() {
    return CommonSearchHistoryState();
  }
}

class CommonSearchHistoryState extends State<CommonSearchHistory> {
  List<SecondSearchItem> historyList;
  FlutterDeviceInfo deviceInfo;

  CommonSearchHistoryState();

  @override
  void initState() {
    super.initState();
    getDeviceInfo()
        .getCacheInfo(CacheInfoKey.STORE_USER, widget.searchData?.cacheKey)
        .then((String value) {
      if (stringEmpty(value)) {
        return;
      }
      setState(() {
        historyList =
            SearchHistoryListBean.fromJson(json.decode(value)).historyList;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          height: 45,
          padding: EdgeInsets.only(left: 16, right: 16),
          child: Row(
            children: <Widget>[
              Expanded(
                child: DkText.simple("历史搜索", 14, Color(0xff333333)),
              ),
              Image.asset(
                R.imagesCommonSearchTrashPng,
                width: 12,
                height: 12,
                fit: BoxFit.fill,
              ),
              InkWell(
                child: Padding(
                  padding: EdgeInsets.only(left: 4),
                  child: DkText.simple(
                    "清空历史搜索",
                    12,
                    Color(0xff999999),
                  ),
                ),
                onTap: () {
                  if (stringEmpty(widget.searchData?.cacheKey)) {
                    return;
                  }
                  getDeviceInfo()
                      .putCacheInfo(CacheInfoKey.STORE_USER,
                          widget.searchData?.cacheKey, "")
                      .then((bool isSuccess) {
                    setState(() {
                      historyList.clear();
                    });
                  });
                },
              ),
            ],
          ),
        ),
        DkDivider(
          DividerOption.horizontal(
            indentStart: 16,
          ),
        ),
        DkVisibilityCompose(
            VisibilityComposeOption.gone((BuildContext childContext) {
          return LineLimitFlow(
            padding: EdgeInsets.all(16),
            spacing: 14,
            runSpacing: 12,
            maxLine: 10,
            children: historyList.map((SecondSearchItem itemContent) {
              return InkWell(
                child: DkRectShadow(ShadowOption(
                  height: 32,
                  padding: EdgeInsets.only(left: 12, right: 12, top: 9),
                  bgColor: Color(0xffebebeb),
                  borderRadius: BorderRadius.circular(2),
                  child: DkText.simple(
                      itemContent.displayName, 12, Color(0xff999999)),
                )),
                onTap: () {
                  if (widget.isDimSearch) {
                    RouteUtil.pop(context, result: {
                      "searchKey": widget.searchData?.dimKey,
                      "searchValue": itemContent.searchValue,
                      "displayName": itemContent.displayName,
                    });
                    return;
                  }
                  widget.eventBus
                      ?.fire(SearchResultEvent(itemContent.displayName));
                  widget.eventBus
                      ?.fire(SetSearchContentEvent(itemContent.displayName));
                },
              );
            }).toList(),
          );
        }, visible: listNotEmpty(historyList))),
      ],
    );
  }

  FlutterDeviceInfo getDeviceInfo() {
    if (objEmpty(deviceInfo)) {
      deviceInfo = FlutterDeviceInfo();
    }
    return deviceInfo;
  }
}

class CommonSearchSelect extends StatelessWidget {
  final SearchData searchData;
  final String inputContent;

  CommonSearchSelect(this.searchData, this.inputContent);

  @override
  Widget build(BuildContext context) {
    return DkVisibilityCompose(
      VisibilityComposeOption.gone(
        (BuildContext context) {
          return ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              SearchItem item = searchData.listData[index];
              return InkWell(
                child: Container(
                  height: 48,
                  // padding: EdgeInsets.only(left: 17.5),
                  child: Column(
                    children: <Widget>[
                      Expanded(
                        child: Row(
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.only(left: 17.5),
                              child: DkText.simple(item?.title, 14, Color(0xff66677a),fontWeight: FontWeight.normal,),
                            ),
                           // DkText.simple(item?.title, 14, Color(0xff66677a),fontWeight: FontWeight.normal,),
                            Expanded(
                              child: Padding(
                                padding: EdgeInsets.only(left: 6, right: 6),
                                child: DkText.simple(
                                    inputContent, 14, Color(0xff53bdc3),fontWeight: FontWeight.normal,),
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.only(right: 15),
                              child: Image.asset(
                                R.imagesCommonRightArrowPng,
                                width: 12,
                                height: 12,
                                fit: BoxFit.fill,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        height: 5,
                        color:  Color(0xffF7F8F9),
                      )
                      // DkDivider(DividerOption.horizontal()),
                    ],
                  ),
                ),
                onTap: () {
                  //二级搜索-特定搜索销售姓名列表
                  //native参数
                  if (stringNotEmpty(item.jumpType) &&
                      item.jumpType == "route") {
                    RouteUtil.goPage(
                      item.route,
                      widgetContext: context,
                      widgetParams: SecondSearchItem(
                        searchKey: item.searchKey,
                        searchValue: inputContent,
                        displayName: inputContent,
                      ).toJson(),
                      widgetResultCallback: (Map<String, dynamic> resultMap) {
                        handleSearchResult(
                          context,
                          SecondSearchItem.fromJson(resultMap),
                        );
                      },
                    );
                    return;
                  }
                  handleSearchResult(
                    context,
                    SecondSearchItem(
                      searchKey: item.searchKey,
                      searchValue: inputContent,
                      displayName: inputContent,
                    ),
                  );
                },
              );
            },
            itemCount: searchData.listData.length,
            shrinkWrap: true,
            controller: ScrollController(keepScrollOffset: false),
          );
        },
        visible: objNotEmpty(searchData) &&
            listNotEmpty(searchData.listData) &&
            stringNotEmpty(inputContent),
      ),
    );
  }

  void handleSearchResult(BuildContext context, SecondSearchItem searchItem) {
    if (objEmpty(context) || objEmpty(searchItem)) {
      return;
    }
    if (stringBlank(searchData.cacheKey)) {
      RouteUtil.pop(context, result: searchItem.toJson());
      return;
    }
    FlutterDeviceInfo deviceInfo = FlutterDeviceInfo();
    deviceInfo
        .getCacheInfo(CacheInfoKey.STORE_USER, searchData.cacheKey)
        .then((String value) {
      List<SecondSearchItem> historyList;
      if (stringNotEmpty(value)) {
        historyList =
            SearchHistoryListBean.fromJson(json.decode(value)).historyList;
      }
      historyList ??= List<SecondSearchItem>();
      if (!historyList.contains(searchItem)) {
        if (historyList.length > 10) {
          historyList.removeAt(0);
        }
        historyList.add(searchItem);
      }
      deviceInfo
          .putCacheInfo(CacheInfoKey.STORE_USER, searchData.cacheKey,
              json.encode(SearchHistoryListBean(historyList: historyList)))
          .then((bool isSuccess) {
        RouteUtil.pop(context, result: searchItem.toJson());
      });
    });
  }
}
